import json
from urllib.parse import quote

from sqlalchemy import create_engine, Column, Integer, String, insert, DateTime
from sqlalchemy.orm import declarative_base, sessionmaker

from drissionDemo.体彩.idtest import Snowflake

# 初始化 Snowflake ID 生成器
snowflake = Snowflake(datacenter_id=1, worker_id=1)

# 原始密码
password = "Wangyu@915398"

# URL 编码密码
encoded_password = quote(password)

# 拼接数据库连接字符串
DATABASE_URI = f"mysql+pymysql://root:{encoded_password}@8.155.30.52:3306/lottery2"

# 创建数据库引擎和会话工厂
engine = create_engine(DATABASE_URI)
Session = sessionmaker(bind=engine)

# 定义 ORM 基类
Base = declarative_base()


# 定义 BaseMatchInformation 表对应的 ORM 模型
class BaseMatchInformation(Base):
    __tablename__ = 'base_match_information'

    match_id = Column(String(32), primary_key=True)  # 比赛唯一标识符
    match_time = Column(String(10))  # 比赛时间
    host_name = Column(String(32))  # 主队名称
    host_scored_num = Column(Integer)  # 主队得分总数
    host_scored_up_num = Column(Integer)  # 主队上半场得分
    host_scored_down_num = Column(Integer)  # 主队下半场得分
    guest_name = Column(String(32))  # 客队名称
    guest_scored_num = Column(Integer)  # 客队得分总数
    guest_scored_up_num = Column(Integer)  # 客队上半场得分
    guest_scored_down_num = Column(Integer)  # 客队下半场得分
    game_attribute = Column(String(32))  # 比赛属性
    internation_attribute = Column(String(32))  # 国际属性
    all_scored = Column(Integer)  # 比赛总得分


# 用于生成插入数据的方法
def generate_data(matches_info):
    """
    根据输入的比赛信息生成 ORM 对象列表，用于插入数据库。

    :param matches_info: 包含比赛信息的字典列表
    :return: ORM 对象列表
    """
    data = []
    for match in matches_info:
        try:
            # 生成唯一的比赛 ID
            match_id = match['id']

            match_time = match.get('matchDate', '')
            host_name = match.get('homeTeamAbbName', '')
            guest_name = match.get('awayTeamAbbName', '')
            game_attribute = match.get('leagueNameAbbr', '')
            internation_attribute = match.get('source', '')

            # 提取并处理比分信息
            try:
                host_scored_num, guest_scored_num = map(int, match.get('sectionsNo999', '0:0').split(':'))
            except ValueError:
                host_scored_num, guest_scored_num = 0, 0

            try:
                host_scored_up_num = int(
                    match.get('sectionsNos', [{'score': '0:0'}])[0].get('score', '0:0').split(':')[0])
                guest_scored_up_num = int(
                    match.get('sectionsNos', [{'score': '0:0'}])[0].get('score', '0:0').split(':')[1])
            except (ValueError, IndexError):
                host_scored_up_num, guest_scored_up_num = 0, 0

            # 计算下半场得分
            host_scored_down_num = host_scored_num - host_scored_up_num
            guest_scored_down_num = guest_scored_num - guest_scored_up_num

            # 总得分
            all_scored = host_scored_num + guest_scored_num

            # 添加生成的 ORM 对象到数据列表
            data.append(BaseMatchInformation(
                match_id=str(match_id),
                match_time=match_time,
                host_name=host_name,
                host_scored_num=host_scored_num,
                host_scored_up_num=host_scored_up_num,
                host_scored_down_num=host_scored_down_num,
                guest_name=guest_name,
                guest_scored_num=guest_scored_num,
                guest_scored_up_num=guest_scored_up_num,
                guest_scored_down_num=guest_scored_down_num,
                game_attribute=game_attribute,
                internation_attribute=internation_attribute,
                all_scored=all_scored
            ))
        except (KeyError, ValueError) as e:
            # 处理数据解析过程中可能出现的错误
            print(f"处理比赛数据时出错: {e}")
    return data


# 插入数据到数据库的方法

def insert_data(data, max_retries=3):
    """
    将生成的 ORM 对象列表插入数据库，并支持失败重试。

    :param data: ORM 对象列表
    :param max_retries: 最大重试次数（默认为 3 次）
    """
    retries = 0
    while retries < max_retries:
        session = Session()
        try:
            # 使用批量保存方式插入数据
            session.bulk_save_objects(data)
            session.commit()
            print("数据插入成功。")
            return  # 插入成功后退出循环
        except SQLAlchemyError as e:
            # 发生异常时回滚事务
            session.rollback()
            retries += 1
            print(f"第 {retries} 次尝试插入数据失败: {e}")
        finally:
            # 关闭会话
            session.close()

    # 如果重试达到最大次数仍失败，记录错误或抛出异常
    print("数据插入失败，已达到最大重试次数。")
    raise Exception("插入数据失败，重试次数已耗尽。")


# 定义胜平负固定奖金初始
class WinningLosingOdds(Base):
    __tablename__ = 'init_winning_losing_odds'

    init_win_flat_negative_id = Column(String(32), primary_key=True)  # 胜平负赔率id
    match_id = Column(String(32), primary_key=True)  # 关联比赛信息id
    init_winning_odds = Column(String(12))  # 胜赔率 (h)
    init_flat_odds = Column(String(12))  # 平赔率 (d)
    init_negative_odds = Column(String(12))  # 负赔率 (a)
    init_win_flat_result = Column(Integer)  # 胜平负结果（3胜 1平 0负）


# 定义胜平负固定奖金最终
class WinningLosingOddsFianal(Base):
    __tablename__ = 'winning_losing_odds'

    win_flat_negative_id = Column(String(32), primary_key=True)  # 胜平负赔率id
    match_id = Column(String(32), primary_key=True)  # 关联比赛信息id
    winning_odds = Column(String(12))  # 胜赔率 (h)
    flat_odds = Column(String(12))  # 平赔率 (d)
    negative_odds = Column(String(12))  # 负赔率 (a)
    win_flat_result = Column(Integer)  # 胜平负结果（3胜 1平 0负）
    flag = Column(String(12))  # 胜平负结果（3胜 1平 0负）


class WinningHHadFianal(Base):
    __tablename__ = 'let_winning_losing_odds'

    let_win_flat_negative_id = Column(String(32), primary_key=True)  # 胜平负赔率id
    match_id = Column(String(32), primary_key=True)  # 关联比赛信息id
    let_winning_odds = Column(String(12))  # 胜赔率 (h)
    let_flat_odds = Column(String(12))  # 平赔率 (d)
    let_negative_odds = Column(String(12))  # 负赔率 (a)
    let_win_flat_result = Column(Integer)  # 胜平负结果（3胜 1平 0负）
    flag = Column(String(12))  # 胜平负结果（3胜 1平 0负）


# 定义 `UnopenedLottery` 表对应的 ORM 模型
class UnopenedLottery(Base):
    __tablename__ = 'unopened_lottery'
    match_id = Column(Integer, primary_key=True, comment='比赛id')
    match_time = Column(DateTime, nullable=True, comment='比赛时间')
    host_name = Column(String(255), nullable=True, comment='主队名称')
    guest_name = Column(String(255), nullable=True, comment='客队名称')
    internation_attribute = Column(String(255), nullable=True, comment='国际类型')
    match_number = Column(String(255), nullable=True, comment='比赛编号')


# 插入数据方法
# def insert_unopenedLottery_data(data):
#     session = Session()  # 创建数据库会话
#     try:
#         # 遍历所有的比赛数据
#         for day in data:
#             # 合并比赛日期和比赛时间
#             match_date = day["比赛日期"]
#             match_time = day["比赛时间"]
#             match_datetime_str = f"{match_date} {match_time}"  # 合并日期和时间
#             match_datetime = datetime.strptime(match_datetime_str, '%Y-%m-%d %H:%M:%S')
#
#             # 创建数据条目
#             entry = UnopenedLottery(
#                 match_id=day["比赛id"],
#                 match_time=match_datetime,  # 将合并后的比赛时间插入
#                 host_name=day["主队简称"],
#                 guest_name=day["客队简称"],
#                 internation_attribute=day["联赛简称"],  # 假设leagueAbbName对应国际类型
#                 match_number=day["比赛编号"]
#             )
#             # 将数据添加到会话
#             session.add(entry)
#         # 提交事务
#         session.commit()
#         print("数据插入成功！")
#
#     except SQLAlchemyError as e:
#         session.rollback()  # 如果出现异常，回滚事务
#         print(f"数据插入失败：{e}")
#     finally:
#         session.close()  # 关闭会话


def generate_odds_data(odds_list):
    """
    根据传入的比赛赔率信息数组生成 ORM 对象列表。

    :param odds_list: 包含多个赔率信息的列表
    :return: 生成的 ORM 对象列表
    """
    # 定义 win_flag_result 的映射
    result_mapping = {
        "胜": 3,
        "平": 1,
        "负": 0,
        "-1": -1
    }

    orm_objects = []
    for odds_info in odds_list:
        try:
            # 生成 win_flat_negative_id
            win_flat_negative_id = str(snowflake.generate_id())

            # 映射赔率字段
            winning_odds = odds_info['h']  # 胜赔率
            flat_odds = odds_info['d']  # 平赔率
            negative_odds = odds_info['a']  # 负赔率

            # 将文字结果映射为数字
            win_flat_result_text = odds_info['win_flag_result']
            if win_flat_result_text not in result_mapping:
                raise ValueError(f"未知的胜平负结果: {win_flat_result_text}")
            win_flat_result = result_mapping[win_flat_result_text]

            # 创建 ORM 对象
            orm_object = WinningLosingOdds(
                init_win_flat_negative_id=win_flat_negative_id,
                match_id=odds_info['id'],  # 比赛 ID
                init_winning_odds=winning_odds,
                init_flat_odds=flat_odds,
                init_negative_odds=negative_odds,
                init_win_flat_result=win_flat_result
            )
            orm_objects.append(orm_object)
        except KeyError as e:
            print(f"数据缺失错误: {e}, 数据: {odds_info}")
        except ValueError as e:
            print(f"数据格式错误: {e}, 数据: {odds_info}")

    return orm_objects


def generate_hhad_dataFinal(odds_list):
    """
    根据传入的比赛赔率信息数组生成 ORM 对象列表。

    :param odds_list: 包含多个赔率信息的列表
    :return: 生成的 ORM 对象列表
    """
    # 定义 win_flag_result 的映射
    result_mapping = {
        "胜": 3,
        "平": 1,
        "负": 0,
        "-1": -1
    }

    orm_objects = []
    for odds_info in odds_list:
        try:
            # 生成 win_flat_negative_id
            let_win_flat_negative_id = str(snowflake.generate_id())

            # 映射赔率字段
            let_winning_odds = odds_info['h']  # 胜赔率
            let_flat_odds = odds_info['d']  # 平赔率
            let_negative_odds = odds_info['a']  # 负赔率

            # 将文字结果映射为数字
            win_flat_result_text = odds_info['win_flag_result']
            flag = odds_info['flag']
            if win_flat_result_text not in result_mapping:
                raise ValueError(f"未知的让胜平负结果: {win_flat_result_text}")
            win_flat_result = result_mapping[win_flat_result_text]

            # 创建 ORM 对象
            orm_object = WinningHHadFianal(
                let_win_flat_negative_id=let_win_flat_negative_id,
                match_id=odds_info['id'],  # 比赛 ID
                let_winning_odds=let_winning_odds,
                let_flat_odds=let_flat_odds,
                let_negative_odds=let_negative_odds,
                let_win_flat_result=win_flat_result,
                flag=flag
            )
            orm_objects.append(orm_object)
        except KeyError as e:
            print(f"数据缺失错误: {e}, 数据: {odds_info}")
        except ValueError as e:
            print(f"数据格式错误: {e}, 数据: {odds_info}")

    return orm_objects


def generate_odds_dataFinal(odds_list):
    """
    根据传入的比赛赔率信息数组生成 ORM 对象列表。

    :param odds_list: 包含多个赔率信息的列表
    :return: 生成的 ORM 对象列表
    """
    # 定义 win_flag_result 的映射
    result_mapping = {
        "胜": 3,
        "平": 1,
        "负": 0,
        "-1": -1
    }

    orm_objects = []
    for odds_info in odds_list:
        try:
            # 生成 win_flat_negative_id
            win_flat_negative_id = str(snowflake.generate_id())

            # 映射赔率字段
            winning_odds = odds_info['h']  # 胜赔率
            flat_odds = odds_info['d']  # 平赔率
            negative_odds = odds_info['a']  # 负赔率

            # 将文字结果映射为数字
            win_flat_result_text = odds_info['win_flag_result']
            flag = odds_info['flag']
            if win_flat_result_text not in result_mapping:
                raise ValueError(f"未知的胜平负结果: {win_flat_result_text}")
            win_flat_result = result_mapping[win_flat_result_text]

            # 创建 ORM 对象
            orm_object = WinningLosingOddsFianal(
                win_flat_negative_id=win_flat_negative_id,
                match_id=odds_info['id'],  # 比赛 ID
                winning_odds=winning_odds,
                flat_odds=flat_odds,
                negative_odds=negative_odds,
                win_flat_result=win_flat_result,
                flag=flag
            )
            orm_objects.append(orm_object)
        except KeyError as e:
            print(f"数据缺失错误: {e}, 数据: {odds_info}")
        except ValueError as e:
            print(f"数据格式错误: {e}, 数据: {odds_info}")

    return orm_objects


def insert_odds_data(orm_objects):
    """
    批量插入胜平负赔率数据到数据库。

    :param orm_objects: ORM 对象列表
    """
    if not orm_objects:
        print("没有可插入的数据。")
        return

    session = Session()
    try:
        # 批量保存数据
        session.bulk_save_objects(orm_objects)
        session.commit()
        print(f"成功插入 {len(orm_objects)} 条胜平负赔率数据。")
    except SQLAlchemyError as e:
        # 出现异常时回滚事务
        session.rollback()
        print(f"数据插入失败: {e}")
    finally:
        # 关闭会话
        session.close()


# 定义 ORM 模型
class BaseTotalGoalOdds(Base):
    __tablename__ = 'init_base_total_goal_odds'

    init_id = Column(String(32), primary_key=True, comment='主键标识')
    match_id = Column(String(32), comment='关联球赛信息id')
    init_zero = Column(String(12), comment='进0球')
    init_one = Column(String(12), comment='进1球')
    init_two = Column(String(12), comment='进2球')
    init_three = Column(String(12), comment='进3球')
    init_four = Column(String(12), comment='进4球')
    init_five = Column(String(12), comment='进5球')
    init_six = Column(String(12), comment='进6球')
    init_seven = Column(String(12), comment='进7球')
    init_all_scored = Column(Integer, nullable=False, comment='进球总数')


class BaseTotalGoalOddsFinal(Base):
    __tablename__ = 'base_total_goal_odds'

    id = Column(String(32), primary_key=True, comment='主键标识')
    match_id = Column(String(32), comment='关联球赛信息id')
    zero = Column(String(12), comment='进0球')
    one = Column(String(12), comment='进1球')
    two = Column(String(12), comment='进2球')
    three = Column(String(12), comment='进3球')
    four = Column(String(12), comment='进4球')
    five = Column(String(12), comment='进5球')
    six = Column(String(12), comment='进6球')
    seven = Column(String(12), comment='进7球')
    flag = Column(String(12))
    all_scored = Column(Integer, nullable=False, comment='进球总数')


from sqlalchemy.exc import SQLAlchemyError


def insert_goal_odds(data_array):
    """
    将总进球赔率数据插入到 base_total_goal_odds 表中。
    
    :param data_array: 包含赔率数据的列表，每个元素是一个字典
    """
    session = Session()
    try:
        for data in data_array:
            data = json.loads(data)
            # 生成 ORM 对象
            record = BaseTotalGoalOdds(
                init_id=str(snowflake.generate_id()),  # 假设 generate_id 是一个唯一 ID 生成工具
                match_id=data.get("id"),
                init_zero=data["0"],
                init_one=data["1"],
                init_two=data["2"],
                init_three=data["3"],
                init_four=data["4"],
                init_five=data["5"],
                init_six=data["6"],
                init_seven=data["7"],
                init_all_scored=data["ttg_combination_desc"]  # 暂不处理总进球数
            )

            # 插入数据
            session.add(record)
        session.commit()
        print("所有数据插入成功！")
    except SQLAlchemyError as e:
        session.rollback()
        print(f"数据库错误: {e}")
    finally:
        session.close()


def insert_goal_oddsFinal(data_array):
    """
    将总进球赔率数据插入到 base_total_goal_odds 表中。
    
    :param data_array: 包含赔率数据的列表，每个元素是一个字典
    """
    session = Session()
    try:
        for data in data_array:
            data = json.loads(data)
            # 生成 ORM 对象
            record = BaseTotalGoalOddsFinal(
                id=str(snowflake.generate_id()),  # 假设 generate_id 是一个唯一 ID 生成工具
                match_id=data.get("id"),
                zero=data["0"],
                one=data["1"],
                two=data["2"],
                three=data["3"],
                four=data["4"],
                five=data["5"],
                six=data["6"],
                seven=data["7"],
                all_scored=data["ttg_combination_desc"],  # 暂不处理总进球数
                flag=data["flag"]  # 暂不处理总进球数
            )

            # 插入数据
            session.add(record)
        session.commit()
        print("所有数据插入成功！")
    except SQLAlchemyError as e:
        session.rollback()
        print(f"数据库错误: {e}")
    finally:
        session.close()


class HalfTheGameTied(Base):
    __tablename__ = 'init_half_the_game_tied'

    init_half_id = Column(String(32), primary_key=True, comment='主键标识半全场胜平负id')
    match_id = Column(String(32), nullable=False, comment='关联球赛信息id')
    init_win_win = Column(String(32), nullable=False, comment='胜胜')
    init_win_flat = Column(String(32), nullable=False, comment='胜平')
    init_win_draw = Column(String(32), nullable=False, comment='胜负')
    init_flat_win = Column(String(32), nullable=False, comment='平胜')
    init_flat_flat = Column(String(32), nullable=False, comment='平平')
    init_flat_draw = Column(String(32), nullable=False, comment='平负')
    init_draw_win = Column(String(32), nullable=False, comment='负胜')
    init_draw_flat = Column(String(32), nullable=False, comment='负平')
    init_draw_draw = Column(String(32), nullable=False, comment='负负')
    init_half_end_result = Column(String(32), nullable=False, comment='最终结果（字典编码half_game_result）')


class HalfTheGameTiedFinal(Base):
    __tablename__ = 'half_the_game_tied'

    half_id = Column(String(32), primary_key=True, comment='主键标识半全场胜平负id')
    match_id = Column(String(32), nullable=False, comment='关联球赛信息id')
    win_win = Column(String(32), nullable=False, comment='胜胜')
    win_flat = Column(String(32), nullable=False, comment='胜平')
    win_draw = Column(String(32), nullable=False, comment='胜负')
    flat_win = Column(String(32), nullable=False, comment='平胜')
    flat_flat = Column(String(32), nullable=False, comment='平平')
    flat_draw = Column(String(32), nullable=False, comment='平负')
    draw_win = Column(String(32), nullable=False, comment='负胜')
    draw_flat = Column(String(32), nullable=False, comment='负平')
    draw_draw = Column(String(32), nullable=False, comment='负负')
    flag = Column(String(12))
    half_end_result = Column(String(32), nullable=False, comment='最终结果（字典编码half_game_result）')


def insert_half_the_game_tied(data_list):
    session = Session()
    try:
        for data in data_list:
            half_id = str(snowflake.generate_id())  # 生成唯一ID

            record = {
                "init_half_id": half_id,
                "match_id": data["id"],
                "init_win_win": data["胜胜"],
                "init_win_flat": data["胜平"],
                "init_win_draw": data["胜负"],
                "init_flat_win": data["平胜"],
                "init_flat_flat": data["平平"],
                "init_flat_draw": data["平负"],
                "init_draw_win": data["负胜"],
                "init_draw_flat": data["负平"],
                "init_draw_draw": data["负负"],
                "init_half_end_result": data["hafu_combination_desc"]
            }

            # 插入数据
            session.execute(
                insert(HalfTheGameTied).values(record)
            )
        session.commit()
        print("数据插入成功！")
    except SQLAlchemyError as e:
        session.rollback()
        print(f"数据库错误: {e}")
    finally:
        session.close()


def insert_half_the_game_tied_final(data_list):
    session = Session()
    try:
        for data in data_list:
            half_id = str(snowflake.generate_id())  # 生成唯一ID

            record = {
                "half_id": half_id,
                "match_id": data["id"],
                "win_win": data["胜胜"],
                "win_flat": data["胜平"],
                "win_draw": data["胜负"],
                "flat_win": data["平胜"],
                "flat_flat": data["平平"],
                "flat_draw": data["平负"],
                "draw_win": data["负胜"],
                "draw_flat": data["负平"],
                "draw_draw": data["负负"],
                "flag": data["flag"],
                "half_end_result": data["hafu_combination_desc"]
            }

            # 插入数据
            session.execute(
                insert(HalfTheGameTiedFinal).values(record)
            )
        session.commit()
        print("数据插入成功！")
    except SQLAlchemyError as e:
        session.rollback()
        print(f"数据库错误: {e}")
    finally:
        session.close()


class ScoreAgainstTable(Base):
    __tablename__ = 'init_score_against_the_odds'
    init_against_id = Column(String(32), primary_key=True)  # '主键表示',
    match_id = Column(String(32))  # '关联主客队比分结果id',
    init_one_zero = Column(String(32))  # '1:0',
    init_two_zero = Column(String(32))  # '2:0',
    init_two_one = Column(String(32))  # '2:1',
    init_three_zero = Column(String(32))  # '3:0',
    init_three_one = Column(String(32))  # '3:1',
    init_three_two = Column(String(32))  # '3:2',
    init_four_zero = Column(String(32))  # '4:0',
    init_four_one = Column(String(32))  # '4:1',
    init_four_two = Column(String(32))  # '4:2',
    init_five_zero = Column(String(32))  # '5:0',
    init_five_one = Column(String(32))  # '5:1',
    init_five_two = Column(String(32))  # '5:2',
    init_win_others = Column(String(32))  # '胜其它',
    init_zero_zero = Column(String(32))  # '0:0',
    init_one_one = Column(String(32))  # '1:1',
    init_two_two = Column(String(32))  # '2:2',
    init_three_three = Column(String(32))  # '3:3',
    init_flat_others = Column(String(32))  # '平其它',
    init_zero_one = Column(String(32))  # '0:1',
    init_zero_two = Column(String(32))  # '0:2',
    init_one_two = Column(String(32))  # '1:2',
    init_zero_three = Column(String(32))  # '0:3',
    init_one_three = Column(String(32))  # '1:3',
    init_two_three = Column(String(32))  # '2:3',
    init_zero_four = Column(String(32))  # '0:4',
    init_one_four = Column(String(32))  # '1:4',
    init_two_four = Column(String(32))  # '2:4',
    init_zero_five = Column(String(32))  # '0:5',
    init_one_five = Column(String(32))  # '1:5',
    init_two_five = Column(String(32))  # '2:5',
    init_draw_others = Column(String(32))  # '负其它',
    init_against_result = Column(String(32))  # '比分'


class ScoreAgainstTableFinal(Base):
    __tablename__ = 'score_against_the_odds'
    against_id = Column(String(32), primary_key=True)  # '主键表示',
    match_id = Column(String(32))  # '关联主客队比分结果id',
    one_zero = Column(String(32))  # '1:0',
    two_zero = Column(String(32))  # '2:0',
    two_one = Column(String(32))  # '2:1',
    three_zero = Column(String(32))  # '3:0',
    three_one = Column(String(32))  # '3:1',
    three_two = Column(String(32))  # '3:2',
    four_zero = Column(String(32))  # '4:0',
    four_one = Column(String(32))  # '4:1',
    four_two = Column(String(32))  # '4:2',
    five_zero = Column(String(32))  # '5:0',
    five_one = Column(String(32))  # '5:1',
    five_two = Column(String(32))  # '5:2',
    win_others = Column(String(32))  # '胜其它',
    zero_zero = Column(String(32))  # '0:0',
    one_one = Column(String(32))  # '1:1',
    two_two = Column(String(32))  # '2:2',
    three_three = Column(String(32))  # '3:3',
    flat_others = Column(String(32))  # '平其它',
    zero_one = Column(String(32))  # '0:1',
    zero_two = Column(String(32))  # '0:2',
    one_two = Column(String(32))  # '1:2',
    zero_three = Column(String(32))  # '0:3',
    one_three = Column(String(32))  # '1:3',
    two_three = Column(String(32))  # '2:3',
    zero_four = Column(String(32))  # '0:4',
    one_four = Column(String(32))  # '1:4',
    two_four = Column(String(32))  # '2:4',
    zero_five = Column(String(32))  # '0:5',
    one_five = Column(String(32))  # '1:5',
    two_five = Column(String(32))  # '2:5',
    draw_others = Column(String(32))  # '负其它',
    against_result = Column(String(32))  # '比分'
    flag = Column(String(32))  # '比分'


# 用于生成插入数据的方法
def generate_data_crs(matches_info):
    """
    根据输入的比赛信息生成 ORM 对象列表，用于插入数据库。

    :param matches_info: 包含比赛信息的字典列表
    :return: ORM 对象列表
    """
    datas = []
    for data in matches_info:
        try:
            crs_id = str(snowflake.generate_id())  # 生成唯一ID
            # 生成唯一的比赛 ID
            match_id = data['id']
            one_zero = data.get('1:0', None),
            two_zero = data.get('2:0', None),
            two_one = data.get('2:1', None),
            three_zero = data.get('3:0', None),
            three_one = data.get('3:1', None),
            three_two = data.get('3:2', None),
            four_zero = data.get('4:0', None),
            four_one = data.get('4:1', None),
            four_two = data.get('4:2', None),
            five_zero = data.get('5:0', None),
            five_one = data.get('5:1', None),
            five_two = data.get('5:2', None),
            win_others = data.get('胜其他', None),
            zero_zero = data.get('0:0', None),
            one_one = data.get('1:1', None),
            two_two = data.get('2:2', None),
            three_three = data.get('3:3', None),
            flat_others = data.get('平其他', None),
            zero_one = data.get('0:1', None),
            zero_two = data.get('0:2', None),
            one_two = data.get('1:2', None),
            zero_three = data.get('0:3', None),
            one_three = data.get('1:3', None),
            two_three = data.get('2:3', None),
            zero_four = data.get('0:4', None),
            one_four = data.get('1:4', None),
            two_four = data.get('2:4', None),
            zero_five = data.get('0:5', None),
            one_five = data.get('1:5', None),
            two_five = data.get('2:5', None),
            draw_others = data.get('负其他', None),
            against_result = data.get("crs_combination_desc")
            # 添加生成的 ORM 对象到数据列表
            datas.append(ScoreAgainstTable(
                init_against_id=str(crs_id),
                match_id=match_id,
                init_one_zero=one_zero,
                init_two_zero=two_zero,
                init_two_one=two_one,
                init_three_zero=three_zero,
                init_three_one=three_one,
                init_three_two=three_two,
                init_four_zero=four_zero,
                init_four_one=four_one,
                init_four_two=four_two,
                init_five_zero=five_zero,
                init_five_one=five_one,
                init_five_two=five_two,
                init_win_others=win_others,
                init_zero_zero=zero_zero,
                init_one_one=one_one,
                init_two_two=two_two,
                init_three_three=three_three,
                init_flat_others=flat_others,
                init_zero_one=zero_one,
                init_zero_two=zero_two,
                init_one_two=one_two,
                init_zero_three=zero_three,
                init_one_three=one_three,
                init_two_three=two_three,
                init_zero_four=zero_four,
                init_one_four=one_four,
                init_two_four=two_four,
                init_zero_five=zero_five,
                init_one_five=one_five,
                init_two_five=two_five,
                init_draw_others=draw_others,
                init_against_result=against_result
            ))
        except (KeyError, ValueError) as e:
            # 处理数据解析过程中可能出现的错误
            print(f"处理比赛数据时出错: {e}")
    return datas


def generate_data_crsFinal(matches_info):
    """
    根据输入的比赛信息生成 ORM 对象列表，用于插入数据库。

    :param matches_info: 包含比赛信息的字典列表
    :return: ORM 对象列表
    """
    datas = []
    for data in matches_info:
        try:
            crs_id = str(snowflake.generate_id())  # 生成唯一ID
            # 生成唯一的比赛 ID
            match_id = data['id']
            one_zero = data.get('1:0', None),
            two_zero = data.get('2:0', None),
            two_one = data.get('2:1', None),
            three_zero = data.get('3:0', None),
            three_one = data.get('3:1', None),
            three_two = data.get('3:2', None),
            four_zero = data.get('4:0', None),
            four_one = data.get('4:1', None),
            four_two = data.get('4:2', None),
            five_zero = data.get('5:0', None),
            five_one = data.get('5:1', None),
            five_two = data.get('5:2', None),
            win_others = data.get('胜其他', None),
            zero_zero = data.get('0:0', None),
            one_one = data.get('1:1', None),
            two_two = data.get('2:2', None),
            three_three = data.get('3:3', None),
            flat_others = data.get('平其他', None),
            zero_one = data.get('0:1', None),
            zero_two = data.get('0:2', None),
            one_two = data.get('1:2', None),
            zero_three = data.get('0:3', None),
            one_three = data.get('1:3', None),
            two_three = data.get('2:3', None),
            zero_four = data.get('0:4', None),
            one_four = data.get('1:4', None),
            two_four = data.get('2:4', None),
            zero_five = data.get('0:5', None),
            one_five = data.get('1:5', None),
            two_five = data.get('2:5', None),
            draw_others = data.get('负其他', None),
            flag = data.get('flag', None),
            against_result = data.get("crs_combination_desc")
            # 添加生成的 ORM 对象到数据列表
            datas.append(ScoreAgainstTableFinal(
                against_id=str(crs_id),
                match_id=match_id,
                one_zero=one_zero,
                two_zero=two_zero,
                two_one=two_one,
                three_zero=three_zero,
                three_one=three_one,
                three_two=three_two,
                four_zero=four_zero,
                four_one=four_one,
                four_two=four_two,
                five_zero=five_zero,
                five_one=five_one,
                five_two=five_two,
                win_others=win_others,
                zero_zero=zero_zero,
                one_one=one_one,
                two_two=two_two,
                three_three=three_three,
                flat_others=flat_others,
                zero_one=zero_one,
                zero_two=zero_two,
                one_two=one_two,
                zero_three=zero_three,
                one_three=one_three,
                two_three=two_three,
                zero_four=zero_four,
                one_four=one_four,
                two_four=two_four,
                zero_five=zero_five,
                one_five=one_five,
                two_five=two_five,
                draw_others=draw_others,
                against_result=against_result,
                flag=flag
            ))
        except (KeyError, ValueError) as e:
            # 处理数据解析过程中可能出现的错误
            print(f"处理比赛数据时出错: {e}")
    return datas
